<?php

namespace app\api\controller;


use app\admin\logic\TestLogic;
use app\api\logic\TrackLogic;
use app\checkbill\logic\CheckMonthFeeLogic;
use app\data\util\MqQueueName;
use app\order\logic\OrderDocumentLogic;
use app\systems\logic\MqTaskPushLogic;
use Throwable;
use think\facade\Db;
use app\common\controller\DBase;

class TiktokPackage
{

    /**
     * @desc 同步更新店铺信息
     * @date 2024-04-17
     */
    public function synShopList(){
         $field = [
                   's.id','s.site_id as shop_id','s.code as shop_code',
                   's.name','s.region','s.seller_type','s.status','b.app_key',
                   'b.app_secret','b.code','b.access_token','b.refresh_token',
                   'b.access_token_expire_in','s.cipher','s.updatetime_order_site as updatetime_order_shop',
                   's.updatetime_order','s.time_zone'
             ];
         $list = Db::name('site')
             ->alias('s')
             ->leftJoin('ba_account b', 's.account_id = b.id')
             ->order('s.id ASC')
             ->field($field)
             ->select()
             ->toArray();
         $data =[];
         foreach($list as $v){
             $data[] = [
                 'name'       =>$v['name'],
                 'region'     =>$v['region'],
                 'seller_type'=>$v['seller_type'],
                 'shop_id'    =>$v['shop_id'],
                 'shop_code'  =>$v['shop_code'],
                 'status'     =>$v['status']==1 ? 'normal' : 'hidden',
                 'cipher'      =>$v['cipher'],
                 'app_key'    =>$v['app_key'],
                 'app_secret'=>$v['app_secret'],
                 'code'      =>$v['code'],
                 'access_token'      =>$v['access_token'],
                 'refresh_token'      =>$v['refresh_token'],
                 'access_token_expire_in'      =>$v['access_token_expire_in'],
                 'updatetime_order_shop'      =>$v['updatetime_order_shop'],
                 'updatetime_order' =>$v['updatetime_order'],
                 'time_zone'      =>$v['time_zone'],
             ];
         }
        return Db::name('shops')->insertAll($data);
    }


    /**
     * @desc 同步更新产品信息
     * @date 2024-04-20
     */
    public function syncProduct(){
        $field = [
            'p.product_id',
            'p.title as product_name',
            'MAX(i.brand) AS sku'
        ];
        $list =Db::name('product2')->alias('p')
            ->leftJoin('ba_productsku_info i', 'p.product_id = i.product_id')
            ->field($field)
            ->group('p.product_id, p.title')
            ->having('sku!=""')
            ->select()
            ->toArray();
        $data =[];
        foreach($list as $v){
            $data[] = [
                'product_name'   =>$v['product_name'],
                'product_id'     =>$v['product_id'],
                'sku'            =>$v['sku'],
                'created_time'   =>date("Y-m-d H:i:s", time()),
            ];
        }
        return Db::name('product')->insertAll($data);
    }


    /**
     * @desc 更新网红订单sku总数
     * @date 2024-06-26
     */
    public function syncSellerSku(){
           $where      = [];
           $time_start = '1717171200';
           $time_end   = '1719759600';
           $where[]    = ['createtime','between', [$time_start, $time_end]];
           $list       = Db::name('orderwh')->field('skuinfo')->where($where)->select();
           $arr        = [];
           foreach($list as $k=>$v){
               $spu            =  explode(',',$v['skuinfo']);
               if(count($spu)>1){
                       foreach($spu as $key =>$value){
                           $arr[]  = get_spu_info($value);
                       }
               }else{
                   $arr[]   = get_spu_info($v['skuinfo']);
               }
           }
        $counts = array_count_values($arr);
        var_export($counts);
    }


    //更新spu信息
    public function update_spu(){
        $list = Db::name('order_info')->field('id,order_id,spu,seller_sku')->select()->toArray();
        echo PHP_EOL . '开始' . PHP_EOL;
        foreach($list as $k=>$v){
            echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
            if(!$v['spu']){
                $spu = $v['seller_sku'] ? get_spu_info($v['seller_sku']):'';
                $createtime = Db::name('order')->where('order_id',$v['order_id'])->value('createtime');
                Db::name('order_info')->where('id',$v['id'])->update(['spu'=>$spu,'createtime'=>$createtime]);
            }
        }
        echo PHP_EOL . '结束' . PHP_EOL;
    }


    //店铺spu月度销量统计
    public function add_spu_sum(){
        $year    = date('Y');
        $month   = date('m');
        $times   = get_month_time($year,$month);
        $month_format  = $month;
        $shops   = Db::name('shops')->field('id')->select()->toArray();
        foreach($shops as $v){
            $v['first'] = $times['first'];
            $v['last']  = $times['last'];
            $shop_info = self::get_spu_num($v);
            if(!$shop_info) continue;
            $totals   = array_column($shop_info, 'total');
            $totalSum = array_sum($totals);
            $insert_arr = [
                'shop_id'     =>$v['id'],
                'date'        =>$year.'-'.$month_format,
                'json'        =>json_encode($shop_info),
                'month_sum'   =>$totalSum,
                'operate_time'=>date("Y-m-d H:i:s", time()),
            ];
            Db::name('product_month_spu')->insert($insert_arr);
        }
    }


    //统计单个店铺的spu
    public function get_spu_num($info){
        $subQuery = Db::name('order_info')
            ->alias('i')
            ->join('ba_order o', 'o.order_id = i.order_id', 'left')
            ->where('o.shop_id', $info['id'])
            ->where('o.status', '<>', 'CANCELLED')
            ->where('o.createtime', '>', $info['first'])
            ->where('o.createtime', '<', $info['last'])
            ->column('i.order_id');
        $result = Db::name('order_info')
            ->whereIn('order_id', $subQuery)
            ->field('spu, order_id, sum(num) AS total')
            ->group('spu')
            ->select();
        return objectToArray($result);
    }



    /**
     * @desc  更新当月数据处理
     * @date 2024-04-25 每1小时一次
     */
    public function update_spu_sum($month){
        $data    = $this->request->get();
        $month   = $data['month'];
        $year    = date('Y');
        $times   = get_month_time($year,$month);
        $month_format  = $month>9 ? $month :'0'.$month;
        $shops   = Db::name('shops')->field('id')->select()->toArray();
        foreach($shops as $v){
            $v['first'] = $times['first'];
            $v['last']  = $times['last'];
            $shop_info = self::get_spu_num($v);
            $totals   = array_column($shop_info, 'total');
            $totalSum = array_sum($totals);
            $update_arr = [
                'json'        =>json_encode($shop_info),
                'month_sum'   =>$totalSum,
                'operate_time'=>date("Y-m-d H:i:s", time()),
            ];
            Db::name('product_month_spu')->where(['shop_id'=>$v['id'],'date'=>$year.'-'.$month_format])->update($update_arr);
        }
    }



    /**
     * @desc  会话消息店铺数据同步
     * @date  2024-04-28
     */
    public function conversations_shop(){
          $shops= Db::name('shops')->select()->toArray();
          $arr  = [];
          foreach($shops as $v){
              $arr[] = [
                  'shop_id'  =>$v['id'],
                  'shop_name'=>$v['name'],
              ];
          }
        Db::name('conversations_shop')->insertAll($arr);
    }

    /**
     * @desc  获取webhook
     * @date  2024-04-28
     */
    public function get_webhook_infos(){
        $t1       = microtime(true);
        $count    = Db::name('webhooks_516')->field('id,post')->where('type', 2)->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;

        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('webhooks_516')->field('id,post')->where('type', 2)->paginate($pageSize)->toArray();
            $arr = []; // 清空数组
            foreach ($list['data'] as $v){
                $info         = json_decode($v['post'], true);
                $config       = Config('Logisticskey.shop_id');
                $tik_shop_id  = $info['shop_id'] ?? '';
                $shop_id      = $config[$tik_shop_id] ?? '0';
                $arr[] = [
                    'order_id'            => $info['data']['order_id'] ?? '',
                    'shop_id'             => $shop_id,
                    'reverse_event_type'  => $info['data']['reverse_event_type'] ?? '',
                    'reverse_order_id'    => $info['data']['reverse_order_id'] ?? '',
                    'reverse_order_status'=> $info['data']['reverse_order_status'] ?? '',
                    'reverse_type'        => $info['data']['reverse_type'] ?? '',
                    'update_time'         => $info['data']['update_time'] ?? '',
                    'timestamp'           => $info['timestamp'] ?? '',
                    'created_time'        => date('Y-m-d H:i:s', time()),
                ];
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
            Db::name('order_refund_webhook')->insertAll($arr);
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }



    /**
     * @desc  spu计算
     * @date  2024-04-29
     */
    public function get_spu_total(){

         $list = Db::name('order_info')->where('spu','=','')->field('id,order_id,seller_sku')->select()->toArray();
         echo PHP_EOL . '开始' . PHP_EOL;
         foreach($list as $k=>$v) {
             echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
             $spu = $v['seller_sku'] ? get_spu_info($v['seller_sku']):'';
             Db::name('order_info')->where('id',$v['id'])->update(['spu'=>$spu]);
         }
        echo PHP_EOL . '结束' . PHP_EOL;
    }





    /**
     * @desc  createtime同步
     * @date  2024-05-06
     */
    public function get_create_time(){
        $t1       = microtime(true);
        $key      = 'get_create_time_webhook';
        $list      = Db::name('webhooks_516')->where('type',2)->field('post')->select()->toArray();
        echo PHP_EOL . '开始' . PHP_EOL;
        foreach($list as &$v){
            $info         = json_decode($v['post'],true);
            $config       = Config('Logisticskey.shop_id');
            $tik_shop_id  = $info['shop_id']??'';
            $shop_id      = $config[$tik_shop_id]??'0';
            $arr = [
                'order_id'            =>$info['data']['order_id']??'',
                'shop_id'             =>$shop_id,
                'reverse_event_type'  =>$info['data']['reverse_event_type']??'',
                'reverse_order_id'    =>$info['data']['reverse_order_id']??'',
                'reverse_order_status'=>$info['data']['reverse_order_status']??'',
                'reverse_type'        =>$info['data']['reverse_type']??'',
                'update_time'         =>$info['data']['update_time']??'',
                'timestamp'           =>$info['timestamp']??'',
                'created_time'        =>date('Y-m-d H:i:s',time()),
            ];
            Db::name('order_refund_webhook')->insert($arr);
        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo  PHP_EOL ."get_create_time-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
    }




    /**
     * @desc  获取sku信息
     * @date  2024-05-29
     */
    public function get_sku_info(){
        $t1        = microtime(true);
        $list      = Db::name('im_conversations')->field('order_id')->select()->toArray();
        echo PHP_EOL . '开始' . PHP_EOL;
        foreach($list as $k=>$v){
            echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
            $res    = (new TestLogic())->get_sku_info($v);
        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo  PHP_EOL ."get_create_time-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
    }



    /**
     * @desc  群发消息
     * @date  2024-05-30
     */
    public function get_batch_send_order(){
        $t1       = microtime(true);
        $where    = [];
        $where[]  = ['o.status', 'not in', ['CANCELLED,ON_HOLD,UNPAID']];
        $field    = ['o.id,o.order_id,o.shop_id,o.createtime,append.user_id as buyer_user_id'];
        $count    = Db::name('order')
            ->alias('o')
            ->leftJoin('ba_order_append append', 'o.order_id = append.order_id')
            ->field('o.id')
            ->where($where)
            ->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);

        try {
            for ($i = 1; $i <= $page; $i++){
                $list   = Db::name('order')
                    ->alias('o')
                    ->leftJoin('ba_order_append append', 'o.order_id = append.order_id')
                    ->field($field)
                    ->where($where)
                    ->limit(($i - 1) * $pageSize, $pageSize)
                    ->select();
                $list = objectToArray($list);
                $insert_arr = [];
                //批量获取店铺IM信息;
                $shop_ids   = array_column($list,'shop_id');
                $shop_ids   = array_values(array_unique($shop_ids));
                $shop_ims   = Db::name('im_shop_template')->whereIn('shop_id',$shop_ids)
                    ->field('shop_id,customer_nickname,customer_avatar,customer_role,customer_im_id')
                    ->select()->toArray();
                $shop_ims_map = array_column($shop_ims,null,'shop_id');

                foreach($list as $v){
                    if(!$v['buyer_user_id']) continue;
                    $shop_ims_info = $shop_ims_map[$v['shop_id']]??[];

                    // 检查订单ID是否重复
                    $existingOrder = Db::name('im_batch_conversations')
                        ->where('order_id', $v['order_id'])
                        ->value('order_id');

                    if ($existingOrder) {
                        // 已存在的订单ID，跳过插入操作
                        continue;
                    }


                    $insert_arr[] = [
                        'shop_id'          =>$v['shop_id'],
                        'order_id'         =>$v['order_id'],
                        'buyer_user_id'    =>$v['buyer_user_id'],
                        'customer_nickname'=>$shop_ims_info['customer_nickname']??'',
                        'customer_avatar'  =>$shop_ims_info['customer_avatar']??'',
                        'customer_role'    =>$shop_ims_info['customer_role']??'',
                        'customer_im_id'   =>$shop_ims_info['customer_im_id']??'',
                        'createtime'       =>$v['createtime']??'',
                        'created_time'     =>date("Y-m-d H:i:s", time()),
                    ];
                }
                echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
                Db::name('im_batch_conversations')->insertAll($insert_arr);
            }
        }catch (Throwable $e){
               echo 7777;
        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }



    /**
     * @desc  更新date日期
     * @date  2024-06-03
     * @author luckyXiong
     */
    public function update_pay_date(){
        $t1        = microtime(true);
        $where     = [];
        $where[]   = ['date','=',''];
        $list      = Db::name('bank_pay_info')->field('id,paid_time')->where($where)->select()->toArray();
        echo PHP_EOL . '开始' . PHP_EOL;
        foreach($list as $k=>$v){
            echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
            //更新数据
            Db::name('bank_pay_info')->where(['id'=>$v['id']])->update(['date'=>date("Y-m", $v['paid_time'])]);
        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo  PHP_EOL ."get_create_time-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
    }


    /**
     * @desc  更新date日期
     * @date  2024-06-03
     * @author luckyXiong
     */
    public function update_shop_id(){
        $t1       = microtime(true);
        $where    = [];
        $field    = ['id,order_id'];
        $count    = Db::name('order_track')
            ->field($field)
            ->where($where)
            ->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);

        try {
            for ($i = 1; $i <= $page; $i++){
                $list   = Db::name('order_track')
                    ->field($field)
                    ->where($where)
                    ->limit(($i - 1) * $pageSize, $pageSize)
                    ->select();
                $list = objectToArray($list);
                foreach($list as $v){
                    $shop_id = Db::name('order')->where('order_id',$v['order_id'])->value('shop_id');
                    Db::name('order_track')->where('order_id',$v['order_id'])->update(['shop_id'=>$shop_id]);
                }
                echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
            }
        }catch (Throwable $e){
            echo 7777;
        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }



    /**
     * @desc  更新date日期
     * @date  2024-06-03
     * @author luckyXiong
     */
    public function update_yunhui_date(){
        $t1        = microtime(true);
        $where     = [];
        $where[]   = ['date','=',''];
        $list      = Db::name('bank_pay_yunhui')->field('id,created_at')->select()->toArray();
        echo PHP_EOL . '开始' . PHP_EOL;
        foreach($list as $k=>$v){
            echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
            //更新数据
            Db::name('bank_pay_yunhui')->where(['id'=>$v['id']])->update(['date'=>date('Y-m', strtotime($v['created_at']))]);
        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo  PHP_EOL ."get_create_time-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
    }


    /**
     * @desc  账单数据
     * @date  2024-06-18
     * @author luckyXiong
     */
    public function update_month_fee(){
        $t1       = microtime(true);
        $where    = [];
        $where[]  = ['import_id','=',61];
        $field    = ['id,json_info'];
        $count    = Db::name('common_system_import_detail')
            ->field($field)
            ->where($where)
            ->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        try {
            for ($i = 1; $i <= $page; $i++){
                $list   = Db::name('common_system_import_detail')
                    ->field($field)
                    ->where($where)
                    ->limit(($i - 1) * $pageSize, $pageSize)
                    ->select();
                $list = objectToArray($list);
                foreach($list as $v){
                    $importValue = json_decode($v['json_info'], true);
                    (new CheckMonthFeeLogic())->import_info($importValue);
                }
                echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
            }
        }catch (Throwable $e){
            echo 7777;
        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
     * @desc  顺丰对账
     * @date  2024-08-26
     * @author zhangheng
     */
    public function Reconciliation_sf(){
        $t1       = microtime(true);
        $executedCount = 0;
        $count    = Db::name('checkbill_sf')
            ->where('reconciliation_status',0)
            ->count();
            // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        // try {
            for ($i = 1; $i <= $page; $i++){
                $list   = Db::name('checkbill_sf')
                    ->where('reconciliation_status',0)
                    ->limit($pageSize)
                    ->select();
                $list = objectToArray($list);
                foreach($list as $v){
                    if($v['code'] == "SELF_PICKUP_EXPRESS"){
                        (new TrackLogic())->reconciliationinfo_sf_self($v);
                    }else{
                        (new TrackLogic())->reconciliationinfo_sf($v);
                    }
                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                }
                // echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
            }
        // }catch (Throwable $e){
        //     echo 7777;
        // }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    /**
     * @desc  全球无忧对账
     * @date  2024-08-26
     * @author zhangheng
     */
    public function Reconciliation_qqwy(){
        $t1       = microtime(true);
        $executedCount = 0;
        $count    = Db::name('checkbill_qqwy')
            ->where('reference_no',">",0)
            ->where('reconciliation_status',0)
            ->count();
            // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        // try {
            for ($i = 1; $i <= $page; $i++){
                $list   = Db::name('checkbill_qqwy')
                    ->where('reference_no',">",0)
                    ->where('reconciliation_status',0)
                    ->limit(($i - 1) * $pageSize, $pageSize)
                    ->select();
                $list = objectToArray($list);
                foreach($list as $v){
                    (new TrackLogic())->reconciliationinfo_qqwy($v);
                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                }
                echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
            }
        // }catch (Throwable $e){
        //     echo 7777;
        // }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }















}
